/*
 * FileUploadPortletControl.java
 *
 * Created on April 10, 2007, 6:45 PM
 *
 * To change this template, choose Tools | Options and locate the template under
 * the Source Creation and Management node. Right-click the template and choose
 * Open. You can then make changes to the template in the Source Editor.
 */

package gestionportlettarifasadmin;
import com.src.computec.facturacion.source.FacturacionSource;
import com.src.computec.radar.base.source.CoreSource;
import com.src.computec.radar.base.util.RandomStringUtils;
import com.sun.faces.portlet.FacesPortlet;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.faces.context.FacesContext;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletConfig;
import javax.portlet.PortletException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.tarifas.fileupload.PortletDiskFileUpload;

/**
 *
 * @author 
 */
public class FileUploadPortletTarifas extends FacesPortlet{
    
    PortletConfig portletConfigCopia;
    
    public void init(PortletConfig portletConfig) throws PortletException {
        super.init(portletConfig);
        this.portletConfigCopia=portletConfig;        
    }
    
    public void processAction(ActionRequest request, ActionResponse response)
    throws PortletException, IOException {
        // Check the request content type to see if it starts with multipart/
        if (!PortletDiskFileUpload.isMultipartContent(request)) {
            //set an error message                       
            FacesContext context =
                    getFacesContextFactory().getFacesContext
                    (portletConfigCopia.getPortletContext(),
                    request, response, getLifecycle());
	  
//              SessionTarifasAdminBean bean_=(SessionTarifasAdminBean)context.getApplication().getVariableResolver().resolveVariable(context.getCurrentInstance(), "SessionTarifasAdminBean");
//              bean_.setUploadedFile(null);
//            context.getExternalContext().getApplicationMap().remove("uploadedFile");
//            context.getExternalContext().getSessionMap().remove("uploadedFile");            
            super.processAction(request, response);
            return;
        }

        PortletDiskFileUpload dfu = new PortletDiskFileUpload();
        File serverFile = null;      
        String fileName ="";
        //maximum allowed file upload size (10 MB)
        dfu.setSizeMax(10 * 1000 * 1000);
        
        //maximum size in memory (vs disk) (100 KB)
        dfu.setSizeThreshold(100 * 1000);
        
        try {
            //get the FileItems
            List fileItems = dfu.parseRequest(request);
            Iterator iter = fileItems.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField()) {
                    //pass along to render request
                    String fieldName = item.getFieldName();
                    String value = item.getString();
                    response.setRenderParameter(fieldName, value);
                } else {
                    //write the uploaded file to a new location
                    String fieldName = item.getFieldName();
                    fileName = item.getName();
                    String extension_=fileName.substring(fileName.length()-3, fileName.length());
                  //  String name_=fileName.substring(0,fileName.length()-4);
                    String name_="fileUpload";
                    String contentType = item.getContentType();
                    long size = item.getSize();
                    response.setRenderParameter("size", Long.toString(size));
                    response.setRenderParameter("contentType", contentType);
//                    String directorio_=FacturacionSource.getInstance().getFacturacionSetupKey("pathArchivosTarifas");         
                 //  String directorio_= "C:\\CargueArchivos\\"+ FacturacionSource.getInstance().getFacturacionSetupKey("pathArchivosTarifas");     
                    String directorio_= CoreSource.getInstance().getUtilidadesSetupKey("folderCargueArchivos")+ FacturacionSource.getInstance().getFacturacionSetupKey("pathArchivosTarifas");     
                    System.out.println("DIRECTORIO:"+directorio_);                    
                    String serverFileName = name_ + RandomStringUtils.randomAlphanumeric(20)+"."+extension_;
                    
//                    String tempDir = System.getProperty("java.io.tmpdir");
//                    System.out.println("TEM DIR:"+tempDir);
//                    String serverFileName = fieldName + "-portlet.tmp";                 
//                     serverFile = new File(tempDir, serverFileName);
                     serverFile = new File(directorio_, serverFileName);
                    item.write(serverFile); 
		    //response.setRenderParameter("directorio", directorio_);
		    response.setRenderParameter("directorio",directorio_.split(serverFile.separator+serverFile.separator));
                    response.setRenderParameter("serverFileName",
                            serverFileName);
		    
		    
		    
		  //  response.setRenderParameter("serverFile", serverFile);
//                    getPortletContext().log(
                    //                      "serverFileName : " + tempDir + "/" + serverFileName);
                }
            }
        } catch (FileUploadException fue) {
            fue.printStackTrace() ;
            String msg = "File Upload Exception: " + fue.getMessage();
            response.setRenderParameter("error", msg);
            //        getPortletContext().log(msg, fue);
        } catch (Exception e) {
            e.printStackTrace();
            String msg = "Exception: " + e.getMessage();
            response.setRenderParameter("error", msg);
            //      getPortletContext().log(msg, e);
        }
        
        super.processAction(request, response);
        FacesContext context =
                getFacesContextFactory().getFacesContext
                (portletConfigCopia.getPortletContext(),
                request, response, getLifecycle());
      
        
     //   SessionTarifasAdminBean bean_=(SessionTarifasAdminBean)context.getApplication().getVariableResolver().resolveVariable(context.getCurrentInstance(), "SessionTarifasAdminBean");
            //SessionTarifasAdminBean bean_=(SessionTarifasAdminBean)this.getBean(context,"SessionTarifasAdminBean");	    
          //  bean_.setUploadedFile(serverFile);                      
    }
    
    Object getBean(FacesContext pContext,String pNameBean){
        return pContext.getApplication().getVariableResolver().resolveVariable(pContext, pNameBean);
    }
}
